package com.xuelangyun.form.api.exterauth.controller;

import java.util.HashMap;
import java.util.Map;

import com.xuelangyun.form.api.exterauth.form.DyAppLoginForm;
import com.xuelangyun.form.common.utils.PageUtils;
import com.xuelangyun.form.common.utils.R;
import com.xuelangyun.form.exterauth.entity.SysExterAppApiEntity;
import com.xuelangyun.form.exterauth.entity.SysExterAppTokenApiEntity;
import com.xuelangyun.form.exterauth.service.ISysExterAppService;
import com.xuelangyun.form.exterauth.service.ISysExterAppTokenService;
import com.xuelangyun.form.exterauth.service.ISysExterLogService;
import com.xuelangyun.form.security.exterauth.annotation.LoginApp;
import com.xuelangyun.form.security.exterauth.annotation.NoLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xuelangyun.form.api.exterauth.form.LogForm;
import com.xuelangyun.form.common.validator.ValidatorUtils;
import com.xuelangyun.form.common.validator.group.AddGroup;

/**
 * 暴露外部API接口
 *
 * @author weiqing.huang
 * @date 2024年5月12日13:50:48
 */
@RequestMapping("exapi")
@RestController
public class ExportApiController {

    @Autowired
    private ISysExterAppService exterAppService;

    @Autowired
    private ISysExterAppTokenService tokenService;

    @Autowired
    private ISysExterLogService logService;


    @PostMapping("/login")
    @NoLogin
    public R<Object> login(@RequestBody DyAppLoginForm form) {

        ValidatorUtils.validateEntity(form, AddGroup.class);

        String ak = form.getAk();
        String sk = form.getSk();

        // 数据库按照AK 和SK 查找记录
        SysExterAppApiEntity app = exterAppService.queryByAkSk(ak, sk);
        if (app == null) {
            return R.error("AK/SK无效");
        }

        // 存在用户 更新token
        SysExterAppTokenApiEntity token = tokenService.generateToken(app.getId(), "app");

        Map<String, Object> map = new HashMap<>();
        map.put("token", token.getToken());
        map.put("expire", token.getExpireTime());

        return R.ok().setData(map);
    }

    @GetMapping("/log")
    public R<Object> logs(@LoginApp SysExterAppApiEntity app, LogForm form) {
        form.setAppname(app.getId());
        PageUtils pu = logService.queryPage(form);
        return R.ok().setData(pu);
    }

}

